package com.dao.UserDaoImp;

import com.dao.UserDao;
import com.pojo.User;
import com.util.DESCoder;
import org.apache.ibatis.session.SqlSession;

import java.util.ArrayList;
import java.util.List;

public class UserDaoImpl implements UserDao {

    public SqlSession sqlSession ;

    public UserDaoImpl(SqlSession sqlSession) {
        this.sqlSession = sqlSession;
    }

    @Override
    public User queryUserByUserName(String username) {
        User user = this.sqlSession.selectOne("queryUserByUserName",username);
        return userE2D(user);
    }

    @Override
    public List<User> queryUserAll() {
        List<User> list = this.sqlSession.selectList("queryUserAll");
        List<User> result = new ArrayList<>();
        for(User user : list){
            result.add(userE2D(user));
        }
        return result;
    }

    @Override
    public void insertUser(User user) {
        this.sqlSession.insert("insertUser",userD2E(user));
    }

    //达到修改密码的功能
    @Override
    public void updateUser(User user) {
        deleteUser(user.getUsername());
        insertUser(user);
        //this.sqlSession.update("updateUser",user);
    }

    @Override
    public void deleteUser(String username) {
        this.sqlSession.delete("deleteUser",username);
    }
    //将加密过的user 转换成  未加密的user
    private User userE2D(User euser){
        User duser = new User();
        try{
            duser.setUsername(euser.getUsername());
            duser.setPassword(decrypt(euser.getPassword(),euser.getKeystr()));
            duser.setKeystr(euser.getKeystr());
        }catch (Exception ex){}
        return duser;
    }
    //将普通的user 转换成  加密的user
    private User userD2E(User duser){
        User euser = new User();
        try{
            String key = DESCoder.initKey();
            euser.setUsername(duser.getUsername());
            euser.setPassword(encrypt(duser.getPassword(),key));
            euser.setKeystr(key);
        }catch (Exception ex){}
        return euser;
    }

    //加密
    private String encrypt(String password , String key) throws Exception{
        return DESCoder.encryptBASE64(DESCoder.encrypt(password.getBytes(),key));
    }
    //解密
    private String decrypt(String passworded,String key)throws Exception{
        return new String(DESCoder.decrypt(DESCoder.decryptBASE64(passworded),key));
    }
}
